// article-detail.js
const { articleAPI } = require('../../interface.js');

Page({
  data: {
    articleId: null,
    articleDetail: null,
    loading: true,
    error: null,
    isPlaying: false,
    backgroundAudioManager: null,
    isLiked: false,
    today_date: '',
    currentTimeGreeting: 'morning'
  },

  onLoad: function (options) {
    // 设置今日日期
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth() + 1;
    const day = today.getDate();
    const todayDate = `${year}年${month}月${day}日`;
    
    // 根据当前时间设置问候语
    const hour = today.getHours();
    let timeGreeting = 'morning';
    if (hour >= 6 && hour < 12) {
      timeGreeting = 'morning';  // 上午好 (6:00-11:59)
    } else if (hour >= 12 && hour < 18) {
      timeGreeting = 'afternoon'; // 下午好 (12:00-17:59)
    } else {
      timeGreeting = 'evening';   // 晚上好 (18:00-5:59)
    }
    
    // 初始化背景音乐管理器
    const backgroundAudioManager = wx.getBackgroundAudioManager();
    this.setData({
      backgroundAudioManager: backgroundAudioManager,
      today_date: todayDate,
      currentTimeGreeting: timeGreeting
    });

    // 监听音乐播放状态
    backgroundAudioManager.onPlay(() => {
      this.setData({ isPlaying: true });
    });

    backgroundAudioManager.onPause(() => {
      this.setData({ isPlaying: false });
    });

    backgroundAudioManager.onStop(() => {
      this.setData({ isPlaying: false });
    });

    backgroundAudioManager.onEnded(() => {
      this.setData({ isPlaying: false });
    });

    if (options.id) {
      this.setData({
        articleId: options.id
      });
      console.log('接收到的文章ID:', options.id);
      this.loadArticleDetail(options.id);
    }
  },

  // 加载文章详情
  loadArticleDetail: function (articleId) {
    this.setData({
      loading: true,
      error: null
    });

    // 如果是测试模式，使用 mock 数据
    // if (articleId === 'mock' || articleId === '33') {
    //   this.loadMockData();
    //   return;
    // }

    articleAPI.getArticleDetail(articleId)
      .then(res => {
        console.log('文章详情数据:', res);
        const articleDetail = res.data;
        this.processArticleData(articleDetail);
      })
      .catch(err => {
        console.error('获取文章详情失败:', err);
        this.setData({
          error: '获取文章详情失败',
          loading: false
        });
        wx.showToast({
          title: '获取文章详情失败',
          icon: 'none'
        });
      });
  },

  // 加载 Mock 数据
  loadMockData: function () {
    const mockData = {
      "code": 200,
      "msg": "获取文章详情成功",
      "data": {
        "id": 33,
        "title": "gif4",
        "description": "gif4gif4gif4gif4",
        "type": "custom",
        "h5_url": null,
        "background_music_id": "file_68ab1b645b4536.09182660",
        "background_animation_id": "file_68ab1b6c8a39a6.76858567",
        "content": [
          {
            "type": "image",
            "file_id": "file_68ab1b5b3ab036.22744093",
            "name": "1.gif",
            "url": "http://jy-video-playback.oss-cn-beijing.aliyuncs.com/uploads/2025/08/24/file_68ab1b5b3ab036.22744093.gif?Expires=2071404123&OSSAccessKeyId=LTAI5t9ft4WH3eefao2iphTh&Signature=2SGYD4tVLl%2FVmYdlX8xjY2K4CnY%3D",
            "thumbnail_url": "http://jy-video-playback.oss-cn-beijing.aliyuncs.com/uploads/2025/08/24/file_68ab1b5b3ab036.22744093.gif?Expires=2071404123&OSSAccessKeyId=LTAI5t9ft4WH3eefao2iphTh&Signature=2SGYD4tVLl%2FVmYdlX8xjY2K4CnY%3D",
            "file_size": 19809,
            "file_type": "image",
            "original_name": "1.gif",
            "order": 0
          },
          {
            "type": "image",
            "file_id": "file_68ab1b5de0eba9.94936037",
            "name": "2.gif",
            "url": "http://jy-video-playback.oss-cn-beijing.aliyuncs.com/uploads/2025/08/24/file_68ab1b5de0eba9.94936037.gif?Expires=2071404126&OSSAccessKeyId=LTAI5t9ft4WH3eefao2iphTh&Signature=d0XmJMUNy7GrM5R%2Fvyy7O5LC77s%3D",
            "thumbnail_url": "http://jy-video-playback.oss-cn-beijing.aliyuncs.com/uploads/2025/08/24/file_68ab1b5de0eba9.94936037.gif?Expires=2071404126&OSSAccessKeyId=LTAI5t9ft4WH3eefao2iphTh&Signature=d0XmJMUNy7GrM5R%2Fvyy7O5LC77s%3D",
            "file_size": 15721,
            "file_type": "image",
            "original_name": "2.gif",
            "order": 1
          },
          {
            "type": "image",
            "file_id": "file_68ab1b6176f5b5.35978980",
            "name": "3.gif",
            "url": "http://jy-video-playback.oss-cn-beijing.aliyuncs.com/uploads/2025/08/24/file_68ab1b6176f5b5.35978980.gif?Expires=2071404129&OSSAccessKeyId=LTAI5t9ft4WH3eefao2iphTh&Signature=jzV%2FrxN8OXHNzFhvODwoUFf6oRA%3D",
            "thumbnail_url": "http://jy-video-playback.oss-cn-beijing.aliyuncs.com/uploads/2025/08/24/file_68ab1b6176f5b5.35978980.gif?Expires=2071404129&OSSAccessKeyId=LTAI5t9ft4WH3eefao2iphTh&Signature=jzV%2FrxN8OXHNzFhvODwoUFf6oRA%3D",
            "file_size": 5550,
            "file_type": "image",
            "original_name": "3.gif",
            "order": 2
          }
        ],
        "status": "published",
        "view_count": 1,
        "like_count": 0,
        "is_featured": false,
        "is_active": true,
        "published_at": "2025-08-24T14:02:42.000000Z",
        "created_at": "2025-08-24T14:02:32.000000Z",
        "updated_at": "2025-08-24T14:02:42.000000Z",
        "background_music": {
          "id": 144,
          "unique_id": "file_68ab1b645b4536.09182660",
          "original_name": "video.mp4",
          "file_name": "file_68ab1b645b4536.09182660.mp4",
          "file_path": "uploads/2025/08/24/file_68ab1b645b4536.09182660.mp4",
          "file_type": "video",
          "mime_type": "video/mp4",
          "file_size": 318465,
          "oss_url": "http://jy-video-playback.oss-cn-beijing.aliyuncs.com/uploads/2025/08/24/file_68ab1b645b4536.09182660.mp4?Expires=2071404132&OSSAccessKeyId=LTAI5t9ft4WH3eefao2iphTh&Signature=GA9%2BigIvHHhJ%2FDf%2BsUxKXlLo9Ho%3D",
          "cdn_url": "",
          "thumbnail_url": "http://jy-video-playback.oss-cn-beijing.aliyuncs.com/uploads/2025/08/24/file_68ab1b645b4536.09182660.mp4?Expires=2071404132&OSSAccessKeyId=LTAI5t9ft4WH3eefao2iphTh&Signature=GA9%2BigIvHHhJ%2FDf%2BsUxKXlLo9Ho%3D",
          "metadata": {
            "width": null,
            "height": null,
            "duration": null
          },
          "created_at": "2025-08-24T14:02:12.000000Z",
          "updated_at": "2025-08-24T14:02:12.000000Z"
        },
        "background_animation": {
          "id": 145,
          "unique_id": "file_68ab1b6c8a39a6.76858567",
          "original_name": "cover.png",
          "file_name": "file_68ab1b6c8a39a6.76858567.png",
          "file_path": "uploads/2025/08/24/file_68ab1b6c8a39a6.76858567.png",
          "file_type": "image",
          "mime_type": "image/png",
          "file_size": 5351434,
          "oss_url": "http://jy-video-playback.oss-cn-beijing.aliyuncs.com/uploads/2025/08/24/file_68ab1b6c8a39a6.76858567.png?Expires=2071404147&OSSAccessKeyId=LTAI5t9ft4WH3eefao2iphTh&Signature=HnQyqkPcEqZVxoML8q4vndxwRF4%3D",
          "cdn_url": "",
          "thumbnail_url": "http://jy-video-playback.oss-cn-beijing.aliyuncs.com/uploads/2025/08/24/file_68ab1b6c8a39a6.76858567.png?Expires=2071404147&OSSAccessKeyId=LTAI5t9ft4WH3eefao2iphTh&Signature=HnQyqkPcEqZVxoML8q4vndxwRF4%3D",
          "metadata": {
            "width": 2560,
            "height": 1080,
            "duration": null
          },
          "created_at": "2025-08-24T14:02:27.000000Z",
          "updated_at": "2025-08-24T14:02:27.000000Z"
        }
      }
    };

    console.log('使用 Mock 数据:', mockData);
    this.processArticleData(mockData.data);
  },

  // 处理文章数据
  processArticleData: function (articleDetail) {
    // 处理文章内容
    if (articleDetail && articleDetail.content && Array.isArray(articleDetail.content)) {
      // 将content数组转换为富文本格式和图片列表
      const { htmlContent, imageList } = this.processArticleContent(articleDetail.content);
      articleDetail.processedContent = htmlContent;
      articleDetail.imageList = imageList;
    }

    // 处理背景图片
    if (articleDetail.background_animation && articleDetail.background_animation.oss_url) {
      articleDetail.background_animation.url = articleDetail.background_animation.oss_url;
    }

    this.setData({
      articleDetail,
      loading: false
    });

    // 动态设置页面标题
    if (articleDetail.title) {
      wx.setNavigationBarTitle({
        title: articleDetail.title
      });
    }

    // 检查点赞状态
    this.checkLikeStatus();

    // 自动播放背景音乐
    if (articleDetail.background_music && articleDetail.background_music.oss_url) {
      this.autoPlayMusic();
    }
  },

  // 处理文章内容
  processArticleContent: function (contentArray) {
    if (!Array.isArray(contentArray)) {
      return { htmlContent: '', imageList: [] };
    }

    // 按order排序
    const sortedContent = contentArray.sort((a, b) => (a.order || 0) - (b.order || 0));

    // 分别处理不同类型的内容
    let htmlContent = '';
    let imageList = [];

    sortedContent.forEach(item => {
      if (item.type === 'html') {
        htmlContent += item.content || '';
      } else if (item.type === 'text') {
        // 将纯文本包装为p标签
        htmlContent += `<p>${item.content || ''}</p>`;
      } else if (item.type === 'image') {
        // 收集图片信息
        imageList.push({
          url: item.url,
          thumbnail_url: item.thumbnail_url,
          name: item.name || item.original_name,
          order: item.order || 0
        });
      }
    });

    return { htmlContent, imageList };
  },

  // 打开H5链接
  openH5Link: function (e) {
    const url = e.currentTarget.dataset.url;
    if (url) {
      wx.navigateTo({
        url: `/pages/webview/webview?url=${encodeURIComponent(url)}`
      });
    } else {
      wx.showToast({
        title: 'H5链接地址无效',
        icon: 'none'
      });
    }
  },

  // 预览图片
  previewImage: function (e) {
    const currentUrl = e.currentTarget.dataset.url;
    const imageList = e.currentTarget.dataset.urls;

    if (currentUrl && imageList) {
      // 提取所有图片的URL
      const urls = imageList.map(item => item.url);

      wx.previewImage({
        current: currentUrl,
        urls: urls
      });
    }
  },

  // 获取第一张图片作为分享图片
  getFirstImage: function () {
    const { articleDetail } = this.data;
    if (articleDetail && articleDetail.content && Array.isArray(articleDetail.content)) {
      // 查找第一张图片
      const firstImageItem = articleDetail.content.find(item => item.type === 'image' && item.url);
      if (firstImageItem) {
        return firstImageItem.url;
      }
    }
    return '';
  },

  // 切换音乐播放状态
  toggleMusic: function () {
    const { backgroundAudioManager, isPlaying, articleDetail } = this.data;

    if (!backgroundAudioManager || !articleDetail.background_music) {
      wx.showToast({
        title: '暂无背景音乐',
        icon: 'none'
      });
      return;
    }

    if (isPlaying) {
      // 暂停播放
      backgroundAudioManager.pause();
    } else {
      // 开始播放
      const music = articleDetail.background_music;
      backgroundAudioManager.title = articleDetail.title || '背景音乐';
      backgroundAudioManager.epname = articleDetail.title || '文章背景音乐';
      backgroundAudioManager.singer = '系统';
      backgroundAudioManager.coverImgUrl = articleDetail.background_animation?.oss_url || '';
      backgroundAudioManager.src = music.oss_url;

      // 设置循环播放
      backgroundAudioManager.loop = true;

      // 开始播放
      backgroundAudioManager.play();
    }
  },

  // 自动播放背景音乐
  autoPlayMusic: function () {
    const { articleDetail, backgroundAudioManager } = this.data;
    if (!articleDetail.background_music || !articleDetail.background_music.oss_url) {
      return;
    }

    try {
      const music = articleDetail.background_music;
      backgroundAudioManager.title = articleDetail.title || '背景音乐';
      backgroundAudioManager.epname = articleDetail.title || '文章背景音乐';
      backgroundAudioManager.singer = '系统';
      backgroundAudioManager.coverImgUrl = articleDetail.background_animation?.oss_url || '';
      backgroundAudioManager.src = music.oss_url;

      // 设置循环播放
      backgroundAudioManager.loop = true;

      // 开始播放
      backgroundAudioManager.play();

      this.setData({
        isPlaying: true
      });
    } catch (error) {
      console.error('自动播放音乐失败:', error);
    }
  },

  // 检查点赞状态
  checkLikeStatus: function () {
    const articleId = this.data.articleId;
    if (!articleId) return;

    try {
      const likedArticles = wx.getStorageSync('likedArticles') || [];
      const isLiked = likedArticles.indexOf(articleId) !== -1;
      this.setData({
        isLiked: isLiked
      });
    } catch (error) {
      console.error('获取点赞状态失败:', error);
    }
  },

  // 点赞功能（不可取消）
    toggleLike: function() {
      const articleId = this.data.articleDetail.id;
      const isLiked = this.data.isLiked;
      if (!articleId) return;
      
      if (isLiked) {
        // 已经点赞，不允许取消
        wx.showToast({
          title: '您已经点过赞了',
          icon: 'none',
          duration: 1500
        });
        return;
      }
      
      // 添加点赞 - 调用API
      wx.showLoading({ title: '点赞中...' });
      
      articleAPI.likeArticle(articleId).then(res => {
        wx.hideLoading();
        if (res.code === 200) {
          this.setData({ isLiked: true });
          wx.showToast({
            title: res.msg || '点赞成功',
            icon: 'success',
            duration: 1500
          });
          
          // 保存到本地存储用于状态回显
          let likedArticles = wx.getStorageSync('likedArticles') || [];
          if (likedArticles.indexOf(articleId) === -1) {
            likedArticles.push(articleId);
            wx.setStorageSync('likedArticles', likedArticles);
          }
        } else {
          wx.showToast({
            title: res.msg || '点赞失败',
            icon: 'none',
            duration: 2000
          });
        }
      }).catch(err => {
        wx.hideLoading();
        console.error('点赞失败:', err);
        wx.showToast({
          title: '点赞失败，请重试',
          icon: 'none',
          duration: 2000
        });
      });
    },

  // 页面卸载时停止音乐
  onUnload: function () {
    const { backgroundAudioManager } = this.data;
    if (backgroundAudioManager) {
      backgroundAudioManager.stop();
    }
  },

  // 分享功能
  onShareAppMessage: function () {
    const { articleDetail } = this.data;
    const shareImage = this.getFirstImage();

    return {
      title: articleDetail ? articleDetail.title : '精彩文章分享',
      path: `/pages/article-detail/article-detail?id=${this.data.articleId}`,
      imageUrl: shareImage
    };
  },

  // 分享到朋友圈

  // 自定义固定区域事件处理
  onCustomAction1: function() {
    console.log('收藏按钮被点击');
    wx.showToast({
      title: '已收藏',
      icon: 'success',
      duration: 1500
    });
  },

  onCustomAction2: function() {
    console.log('评论按钮被点击');
    wx.showToast({
      title: '评论功能开发中',
      icon: 'none',
      duration: 1500
    });
  },

  onShareTimeline: function () {
    const { articleDetail } = this.data;
    const shareImage = this.getFirstImage();

    return {
      title: articleDetail ? articleDetail.title : '精彩文章分享',
      query: `id=${this.data.articleId}`,
      imageUrl: shareImage
    };
  },

  adLoad() {
    console.log('原生模板广告加载成功')
  },
  adError(err) {
    console.error('原生模板广告加载失败', err)
  },
  adClose() {
    console.log('原生模板广告关闭')
  },
});